import re
from flask_cors import CORS
from sqlite_3 import simpleToolSql
from flask import Flask, g, jsonify
from flask_httpauth import HTTPBasicAuth
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from itsdangerous import BadSignature, SignatureExpired
from gennerate_token import verify_auth_token, generate_auth_token

app = Flask(__name__)
CORS(app, supports_credentials=True)
auth = HTTPBasicAuth()

# 连接数据库操作
def get_info(user_id, password):
    sql = simpleToolSql("test_db")
    command = f"SELECT user_id FROM koukou WHERE user_id = '{user_id}' AND pwd = '{password}'"
    result = sql.query(command, get_one=True)
    if result:
        result = result[0]
    return result

# 验证token
@auth.verify_password
def verify_password(username, password):
    # 先验证token
    user_id = re.sub(r'^"|"$', '', username)
    user_id = verify_auth_token(user_id)
    # 如果token不存在，验证用户id与密码是否匹配
    if not user_id:
        user_id = get_info(username, password)
        if not user_id:
            # 用户id与密码对应不上
            return False
    g.user_id = user_id
    return True

@app.route('/login')
@auth.login_required
def login():
    token = generate_auth_token(g.user_id)
    return jsonify({'token': token})


@app.route('/index')
@auth.login_required
def index():
    return 'index'


if __name__ == '__main__':
    app.run("192.168.57.209", "5000")
